package com.dabai.iot.mqtt.util;

import com.dabai.iot.mqtt.model.ServerConnectionSession;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.SetMultimap;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务端连接会话管理
 *
 * @author kev1n
 */
public class ServerConnectionSessionManager {

    /**
     * sessionMap，其中 key 为消费组 groupID
     */
    public static final SetMultimap<String, ServerConnectionSession> sessionMap = LinkedHashMultimap.create();

    private static class SingletonInstance {
        private static final ServerConnectionSessionManager instance = new ServerConnectionSessionManager();
    }

    private ServerConnectionSessionManager() {
    }

    public static ServerConnectionSessionManager getInstance() {
        return SingletonInstance.instance;
    }

    public boolean containsKey(String groupID) {
        return sessionMap.containsKey(groupID);
    }

    /**
     * 添加会话
     *
     * @param groupID 消费组ID
     * @param session 会话
     */
    public synchronized void addSession(String groupID, ServerConnectionSession session) {
        sessionMap.put(groupID, session);
    }

    /**
     * 获取会话
     *
     * @param groupID
     */
    public List<ServerConnectionSession> getSession(String groupID) {
        if (containsKey(groupID)) {
            return new ArrayList<>(sessionMap.get(groupID));
        }

        return null;
    }

    /**
     * 移除会话
     *
     * @param groupID
     */
    public void removeSession(String groupID, ServerConnectionSession session) {
        sessionMap.remove(groupID, session);
    }

    /**
     * 移除全部
     *
     * @param groupID
     */
    public void removeSession(String groupID) {
        sessionMap.removeAll(groupID);
    }

}
